<template>
  <!-- 路由出口 -->
  <router-view v-slot="{ Component }">
    <transition :name="transitionName" @before-enter="beforeEnter" @after-leave="afterLeave">
      <keep-alive :include="virtualTaskStack">
        <component :key="$route.fullPath" :class="{ 'fixed top-0 left-0 w-screen z-50': isAnimation }" :is="Component" />
      </keep-alive>
    </transition>
  </router-view>
</template>

<script>
const NONE = 'none'
const ROUTER_TYPE_PUSH = 'push'
const ROUTER_TYPE_BACK = 'back'

const ROUTER_TYPE_ENUM = [NONE, ROUTER_TYPE_PUSH, ROUTER_TYPE_BACK]
</script>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
const router = useRouter()

const props = defineProps({
  routerType: {
    type: String,
    default: 'NONE',
    validator: (value) => {
      const result = ROUTER_TYPE_ENUM.includes(value)
      if (!result) {
        throw new Error(`routerType 必须是 ${ROUTER_TYPE_ENUM.join(',')}其中的一个`)
      }
      return result
    }
  },
  // 首页的组件名称，对应任务栈中的第一个组件
  mainComponentName: {
    type: String,
    required: true
  }
})

// 定义动画名字
const transitionName = ref('')

// 路由前置收尾
router.beforeEach((to) => {
  transitionName.value = props.routerType
  // 如果是后退，就把最后一个组件从任务栈中移除
  // 如果是前进，就把当前组件添加到任务栈中
  if (props.routerType === ROUTER_TYPE_BACK) {
    virtualTaskStack.value.pop()
  } else if (props.routerType === ROUTER_TYPE_PUSH) {
    virtualTaskStack.value.push(to.name)
  }
  // 如果进入了首页清空栈
  if (to.name === props.mainComponentName) {
    clearTaskStack()
  }
})

const isAnimation = ref(false)

// 动画开始前
const beforeEnter = () => {
  isAnimation.value = true
}

// 动画结束后
const afterLeave = () => {
  isAnimation.value = false
}

// 利用一个虚拟任务栈的数组 include属性控制keep-alive需要缓存的组件
const virtualTaskStack = ref([props.mainComponentName])
// 清空栈
const clearTaskStack = () => {
  virtualTaskStack.value = [props.mainComponentName]
}
</script>

<style lang="scss" scoped>
// push页面时：新页面的进入动画
.push-enter-active {
  animation-name: push-in;
  animation-duration: 0.5s;
}

// push页面时：老页面的退出动画
.push-leave-active {
  animation-name: push-out;
  animation-duration: 0.5s;
}

// push页面时：新页面的进入动画
@keyframes push-in {
  0% {
    transform: translate(100%, 0);
  }

  100% {
    transform: translate(0, 0);
  }
}

// push页面时：老页面的退出动画
@keyframes push-out {
  0% {
    transform: translate(0, 0);
  }

  100% {
    transform: translate(-50%, 0);
  }
}

// 后退页面时：即将展示的页面动画
.back-enter-active {
  animation-name: back-in;
  animation-duration: 0.4s;
}

// 后退页面时：后退的页面执行的动画
.back-leave-active {
  animation-name: back-out;
  animation-duration: 0.4s;
}

// 后退页面时：即将展示的页面动画
@keyframes back-in {
  0% {
    width: 100%;
    transform: translate(-100%, 0);
  }

  100% {
    width: 100%;
    transform: translate(0, 0);
  }
}

// 后退页面时：后退的页面执行的动画
@keyframes back-out {
  0% {
    width: 100%;
    transform: translate(0, 0);
  }

  100% {
    width: 100%;
    transform: translate(50%, 0);
  }
}
</style>
